import axios from "axios";
import router from "@/router/index";
import {Message} from "element-ui";

const request = axios.create({
  baseURL: "/api",
  timeout: 600000,
});

let hasTokenErrorShown = false;

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 配置不需要登录的地址
    const whiteList = ['/login', '/captchaImage','/send/code','/loginEmail'];
    const url = config.url;

    const isPublicPath = whiteList.some(path => url.includes(path));

    if (!isPublicPath) {
      const token = localStorage.getItem("token");
      if (!token) {
        if (!hasTokenErrorShown) {
          Message.error("请先登录");
          hasTokenErrorShown = true;
          router.push({name: "Login"});
        }
        return Promise.reject(new Error("无 token"));
      }
      config.headers["Authorization"] = 'Bearer ' + token;
    }

    hasTokenErrorShown = false;

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error.response) {
      const status = error.response.status;

      if (status === 401) {
        Message.error("你没有权限/未登录");
        router.push({name: "Login"});
      } else if (status === 404) {
        Message.error("接口不存在");
      } else if (status >= 500) {
        Message.error("服务器异常，请稍后再试");
      } else {
        Message.error("接口访问异常");
      }
    } else if (error.request) {
      Message.error("网络异常，请检查网络连接");
    } else {
      Message.error(`请求异常：${error.message}`);
    }

    return Promise.reject(error);
  }
);

export default request;
